import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lib_core/customization/flutter/cupertino/text_selection.dart';
import 'package:lib_uikit/dimen/gt_dimensions_v3.dart';
import 'package:lib_uikit/lib_uikit.dart';
import 'package:lib_uikit/widgets/gt_dropdown_v3.dart';

enum GTTextFieldTypeV3 { stroke, fill, stoke_e5e5e5 }

//输入框高度：分别对应30，40，44, 52
enum GTTextFieldSizeV3 { small, medium, large, xlarge }

class GTTextFieldV3 extends StatefulWidget {
  final String? hint;
  final ValueChanged<String>? onTextChanged;
  final String? text;
  final VoidCallback? onEndPressed;
  final VoidCallback? onSecondEndPressed;

  //最右边控件
  final Widget? endIcon;

  //最右边第二个控件
  final Widget? endSecondIcon;

  //左边icon
  final Widget? startIcon;
  final GTTextFieldTypeV3? textFieldType;
  final GTTextFieldSizeV3? textFieldSize;

  final String? title;
  final String? bottomText;

  final bool? errorStatus;

  //最右边两个控件中间的分割线，如果是text控件，需要展示分割线，Icon控件不需要
  final bool? showLine;
  final bool? isEnable;
  final bool? contentShowCenter;
  final TextInputType? inputType;
  final List<TextInputFormatter>? inputFormatter;
  final bool? obscureText;
  final TextEditingController? textEditingController;
  final FocusNode? focusNode;
  final Iterable<String>? autofillHints;
  final VoidCallback? editingCompleteCallBack;
  final String? endDropdownText;
  final String? startDropdownText;
  final String? startCoinUrl;
  final String? endCoinUrl;

  //焦点变化监听
  final ValueChanged<bool>? onFocusChanged;

  //展示Title红色星号
  final bool? showTitleMarket;

  const GTTextFieldV3({
    super.key,
    this.hint,
    this.onTextChanged,
    this.autofillHints,
    this.text,
    this.onEndPressed,
    this.onSecondEndPressed,
    this.endIcon,
    this.endSecondIcon,
    this.startIcon,
    this.textFieldSize = GTTextFieldSizeV3.medium,
    this.textFieldType = GTTextFieldTypeV3.fill,
    this.title,
    this.bottomText,
    this.errorStatus,
    this.showLine,
    this.isEnable = true,
    this.contentShowCenter = false,
    this.inputType = TextInputType.text,
    this.inputFormatter,
    this.obscureText = false,
    this.editingCompleteCallBack,
    this.focusNode,
    this.textEditingController,
    this.startDropdownText,
    this.endDropdownText,
    this.startCoinUrl,
    this.endCoinUrl,
    this.onFocusChanged,
    this.showTitleMarket,
  });

  @override
  State<StatefulWidget> createState() => _TextFieldStateV3();
}

class _TextFieldStateV3 extends State<GTTextFieldV3> {
  Color strokeColor = GTColorsV3.neutral5.color;
  bool hasFocus = false;
  late TextEditingController _textEditingController;
  late FocusNode _focusNode;
  bool isShowDelete = false;

  @override
  void initState() {
    _focusNode = widget.focusNode ?? FocusNode();
    _textEditingController =
        widget.textEditingController ?? TextEditingController();
    super.initState();
    if (widget.text != null) {
      _textEditingController.text = widget.text ?? "";
    }
    _focusNode.addListener(_onFocusChange);
    // textEditingController.text = 自动填充 onChanged回调监听不到
    _textEditingController.addListener(textChange);
  }

  @override
  void didUpdateWidget(covariant GTTextFieldV3 oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.text != null) {
      _textEditingController.text = widget.text ?? "";
    }
  }

  void textChange() {
    isShowDelete = _textEditingController.text.isNotEmpty;
  }

  void _onFocusChange() {
    setState(() {
      hasFocus = _focusNode.hasFocus;
    });
    widget.onFocusChanged?.call(hasFocus);
  }

  @override
  void dispose() {
    // 释放资源 外部传入的 外部释放
    if (widget.focusNode == null) {
      _focusNode.dispose();
    }
    _textEditingController.removeListener(textChange);
    if (widget.textEditingController == null) {
      _textEditingController.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    bool _errorStatus = widget.errorStatus ?? false;
    bool _isEnable = widget.isEnable ?? true;
    GTTextFieldTypeV3 textFieldType =
        widget.textFieldType ?? GTTextFieldTypeV3.fill;
    GTTextFieldSizeV3 textFieldSize =
        widget.textFieldSize ?? GTTextFieldSizeV3.medium;
    bool _contentShowCenter = widget.contentShowCenter ?? false;

    Color strokeColor;
    Color backgroundColor;
    double inputHeight;
    switch (textFieldType) {
      case GTTextFieldTypeV3.fill:
        strokeColor = GTColorsV3.neutral5.color;
        backgroundColor = GTColorsV3.neutral5.color;
        break;
      case GTTextFieldTypeV3.stroke:
        strokeColor =
            hasFocus ? GTColorsV3.icon9.color : GTColorsV3.divider5.color;
        backgroundColor = GTColorsV3.bg1.color;
        break;
      case GTTextFieldTypeV3.stoke_e5e5e5:
        strokeColor = hasFocus
            ? GTColorsV3.icon9.color
            : GTColorsV3.divider5.color.withOpacity(0.5);
        backgroundColor = GTColorsV3.bg1.color;
        break;
    }
    if (_errorStatus) {
      strokeColor = GTColorsV3.funct3.color;
    }
    if (!_isEnable) {
      strokeColor = GTColorsV3.cmpt2.color;
      backgroundColor = GTColorsV3.cmpt2.color;
    }

    double titleSize = 14;
    switch (textFieldSize) {
      case GTTextFieldSizeV3.small:
        inputHeight = 30;

        break;
      case GTTextFieldSizeV3.medium:
        inputHeight = 40;
        break;
      case GTTextFieldSizeV3.large:
        titleSize = 13;
        inputHeight = 44;
        break;
      case GTTextFieldSizeV3.xlarge:
        titleSize = 14;
        inputHeight = 52;

        break;
    }
    return Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          if (widget.title != null) ...[
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  widget.title ?? "",
                  style: gtTextStyleW400(
                      fontSize: titleSize, color: GTColorsV3.text1.color),
                ),
                if (widget.showTitleMarket ?? false) ...[
                  const SizedBox(
                    width: 4,
                  ),
                  Text(
                    "*",
                    style: gtTextStyleW400(
                        fontSize: titleSize, color: GTColorsV3.color3.color),
                  ),
                ]
              ],
            ),
            const SizedBox(
              height: 6,
            )
          ],
          Container(
            alignment: Alignment.center,
            height: inputHeight,
            padding: const EdgeInsets.symmetric(horizontal: 12.0),
            decoration: BoxDecoration(
              color: backgroundColor,
              border: Border.all(
                color: strokeColor,
                width: GTDimensionsV3.strokeWidth,
              ),
              borderRadius: BorderRadius.circular(6),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                if (widget.startIcon != null) ...[
                  widget.startIcon!,
                  const SizedBox(width: 8),
                ],
                if ((widget.startDropdownText ?? "").isNotEmpty) ...[
                  GTDropdownV3(
                    text: widget.startDropdownText ?? "",
                    size: GTDropdownSizeV3.size20,
                    textFieldType: true,
                    imagePath: widget.startCoinUrl,
                  ),
                  const SizedBox(width: 8),
                  Container(
                    width: 1,
                    height: 14,
                    color: GTColorsV3.divider4.color,
                  ),
                  const SizedBox(width: 8),
                ],
                Expanded(
                  child: Align(
                    alignment: Alignment.center,
                    child: TextField(
                      autofillHints: widget.autofillHints,
                      obscureText: widget.obscureText ?? false,
                      selectionControls: gtCupertinoTextSelectionControls,
                      textAlign: _contentShowCenter
                          ? TextAlign.center
                          : TextAlign.start,
                      keyboardType: widget.inputType,
                      inputFormatters: widget.inputFormatter,
                      enabled: _isEnable,
                      controller: _textEditingController,
                      focusNode: _focusNode,
                      cursorColor: GTColorsV3.icon5.color,
                      cursorWidth: 2,
                      cursorRadius: const Radius.circular(2),
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: widget.hint,
                        isCollapsed: true,
                        hintStyle: gtTextStyleW500(
                          fontSize: titleSize,
                          color: _isEnable
                              ? hasFocus
                                  ? GTColorsV3.text4.color
                                  : GTColorsV3.text3.color
                              : GTColorsV3.text7.color,
                        ),
                        suffixIconConstraints: BoxConstraints(),
                        suffixIcon: isShowDelete && hasFocus
                            ? GestureDetector(
                                onTap: () {
                                  _textEditingController.clear();
                                  setState(() {
                                    isShowDelete = false;
                                    //点击删除icon把onTextChanged回调返回的text置空
                                    widget.onTextChanged?.call("");
                                  });
                                },
                                child: Icon(
                                  GTIconFont.e807,
                                  size: 16,
                                  color: GTColorsV3.icon3.color,
                                ),
                              )
                            : null,
                      ),
                      onChanged: (text) {
                        setState(() {
                          widget.onTextChanged?.call(text);
                        });
                      },
                      onEditingComplete: () {
                        widget.editingCompleteCallBack?.call();
                      },
                      style: gtTextStyleW500(
                        fontSize: titleSize,
                        color: _isEnable
                            ? GTColorsV3.text1.color
                            : GTColorsV3.text7.color,
                      ),
                    ),
                  ),
                ),
                if (widget.endSecondIcon != null) ...[
                  const SizedBox(width: 12),
                  GestureDetector(
                    onTap: () {
                      widget.onSecondEndPressed?.call();
                    },
                    child: widget.endSecondIcon!,
                  ),
                  SizedBox(width: (widget.showLine ?? false) ? 8 : 6),
                ],
                if (widget.showLine ?? false) ...[
                  Container(
                    width: 1,
                    height: 14,
                    color: GTColorsV3.divider4.color,
                  ),
                ],
                if (widget.endIcon != null) ...[
                  SizedBox(width: (widget.showLine ?? false) ? 8 : 6),
                  GestureDetector(
                    onTap: () {
                      widget.onEndPressed?.call();
                    },
                    child: widget.endIcon!,
                  ),
                ],
              ],
            ),
          ),
          if (widget.bottomText != null) ...[
            const SizedBox(
              height: 6,
            ),
            Text(
              widget.bottomText ?? "",
              style: gtTextStyleW400(
                  fontSize: 12,
                  color: _errorStatus
                      ? GTColorsV3.funct3.color
                      : GTColorsV3.text3.color),
            )
          ],
        ]);
  }
}
